package com.baijiayun.live.ui.topmenu

import androidx.lifecycle.Observer
import android.os.Bundle
import androidx.core.content.ContextCompat
import android.text.TextUtils
import android.view.View
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.activity.LiveRoomBaseActivity
import com.baijiayun.live.ui.base.BasePadFragment
import com.baijiayun.live.ui.base.getViewModel
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.context.LiveRoom
import com.baijiayun.livecore.models.LPCloudRecordModel
import com.baijiayun.livecore.models.LPCloudRecordModel.LPRecordValueModel
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder
import kotlinx.android.synthetic.main.fragment_pad_top_menu.*

/**
 * Created by Shubo on 2019-10-10.
 */
class TopMenuFragment : BasePadFragment() {

    private val topMenuViewModel by lazy { getViewModel { TopMenuViewModel(routerViewModel.liveRoom) } }
    private var isFirstCallRecordStatus = true
    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                fragment_pad_top_menu_title.text = routerViewModel.liveRoom.roomTitle
                topMenuViewModel.subscribe()
                initSuccess()
            }
        }
    }

    companion object {
        fun newInstance() = TopMenuFragment()
    }

    override fun getLayoutId(): Int = R.layout.fragment_pad_top_menu

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    override fun observeActions() {
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
        topMenuViewModel.classStartTimeDesc.observe(this, Observer {
            fragment_pad_top_menu_time.text = it
        })
        topMenuViewModel.showToast.observe(this, Observer {
            it?.let {
                showToastMessage(it)
            }
        })
        topMenuViewModel.recordStatus.observe(this, Observer {
            it?.let {
                fragment_pad_top_menu_record.isChecked = it.status == LPCloudRecordModel.RECORD_STATUS_RECORDING
                if (isFirstCallRecordStatus && it.status != LPCloudRecordModel.RECORD_STATUS_RECORDING) {
                    return@let
                }
                isFirstCallRecordStatus = true
                val needToShow = getNeedShowMessage(routerViewModel.liveRoom, it)
                if (!TextUtils.isEmpty(needToShow) && !routerViewModel.liveRoom.partnerConfig.useSecretCloudRecord) {
                    showToastMessage(needToShow)
                }
            }
        })
        topMenuViewModel.downLinkLossRate.observe(this, Observer {
            it?.let {
                fragment_pad_top_menu_downlossrate.text = it.first
                context?.run {
                    fragment_pad_top_menu_downlossrate.setTextColor(ContextCompat.getColor(this, it.second))
                }
            }
        })
        topMenuViewModel.upLinkLossRate.observe(this, Observer {
            it?.let {
                fragment_pad_top_menu_uplossrate.text = it.first
                context?.run {
                    fragment_pad_top_menu_uplossrate.setTextColor(ContextCompat.getColor(this, it.second))
                }
            }
        })
    }

    private fun getNeedShowMessage(liveRoom: LiveRoom, nowStatus: LPRecordValueModel): String {
        return if (!liveRoom.isTeacherOrAssistant) "" else (
                (if (nowStatus.operator == LPConstants.LPUserType.Teacher && !liveRoom.isTeacher) "老师" else (
                        if (nowStatus.operator == LPConstants.LPUserType.Assistant && liveRoom.isTeacher) "助教" else ""
                        )) + "已" + (if (nowStatus.status == LPCloudRecordModel.RECORD_STATUS_RECORDING) "开启" else "停止") + "云端录制")
    }

    private fun initSuccess() {
        if (routerViewModel.liveRoom.isAudition) {
            fragment_pad_top_menu_setting.visibility = View.GONE
        }
        //老师助教与学生读取不同配置项
        fragment_pad_top_menu_record.visibility =
            if (routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Student || routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Visitor) {
                if (routerViewModel.liveRoom.partnerConfig.liveHideRecordStatus == 1 || routerViewModel.liveRoom.partnerConfig.useSecretCloudRecord) View.GONE
                else View.VISIBLE
            } else {
                if (routerViewModel.liveRoom.partnerConfig.disableLiveRoomBottomMenus.split(",").contains("cloud_record") || routerViewModel.liveRoom.partnerConfig.useSecretCloudRecord) View.GONE
                else View.VISIBLE
            }
        routerViewModel.isShowShare.observe(this, Observer {
            it?.let {
                fragment_pad_top_menu_share.visibility = if (it && routerViewModel.liveRoom.featureConfig?.isShareEnable == true) View.VISIBLE else View.GONE
            }
        })
    }

    private fun initView() {
        fragment_pad_top_menu_exit.setOnClickListener {
            if (LiveRoomBaseActivity.getExitListener() != null) {
                activity?.finish()
            } else {
                routerViewModel.actionExit.value = Unit
            }
        }
        fragment_pad_top_menu_setting.setOnClickListener {
            routerViewModel.action2Setting.value = Unit
        }
        fragment_pad_top_menu_share.setOnClickListener { routerViewModel.action2Share.value = Unit }
        fragment_pad_top_menu_record.setOnClickListener {
            if (routerViewModel.liveRoom.currentUser.type != LPConstants.LPUserType.Teacher
                && routerViewModel.liveRoom.currentUser.type != LPConstants.LPUserType.Assistant
            ) {
                return@setOnClickListener
            }
            if (routerViewModel.isClassStarted.value != true) {
                if (routerViewModel.liveRoom.isTeacher) {
                    showToastMessage(getString(R.string.pad_class_start_tip))
                } else {
                    showToastMessage(getString(R.string.live_course_not_begin))
                }
                return@setOnClickListener
            }
            if (if (topMenuViewModel.recordStatus.value == null) false else topMenuViewModel.recordStatus.value?.status == LPCloudRecordModel.RECORD_STATUS_RECORDING) {
                context?.let {
                    ThemeMaterialDialogBuilder(it)
                        .apply {
                            title(getString(R.string.live_exit_hint_title))
                            content(getString(R.string.live_cloud_recording_content))
                            contentColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_assistant_text_color))
                        }
                        .apply {
                            positiveText(getString(R.string.live_cloud_record_setting_end))
                            positiveColorRes(R.color.base_warning_color)
                            onPositive { _, _ -> topMenuViewModel.switchCloudRecord() }
                        }
                        .apply {
                            negativeText(getString(R.string.live_cancel))
                            onNegative { dialog, _ -> dialog.dismiss() }
                        }
                        .build().show()
                }
            } else {
                topMenuViewModel.switchCloudRecord()
            }
        }
        context?.let {
            val upLinkDrawable = VectorDrawableCompat.create(resources, R.drawable.base_ic_uplink_pad, null)
            upLinkDrawable?.setBounds(0, 0, DisplayUtils.dip2px(it, 16f), DisplayUtils.dip2px(it, 16f))
            fragment_pad_top_menu_uplossrate.setCompoundDrawables(upLinkDrawable, null, null, null)
            val downLinkDrawable = VectorDrawableCompat.create(resources, R.drawable.base_ic_downlink_pad, null)
            downLinkDrawable?.setBounds(0, 0, DisplayUtils.dip2px(it, 16f), DisplayUtils.dip2px(it, 16f))
            fragment_pad_top_menu_downlossrate.setCompoundDrawables(downLinkDrawable, null, null, null)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
    }

    override fun init(view: View) {
        // do nothing
    }
}